package com.newer.veryweather.db;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import com.newer.veryweather.R;
import com.newer.veryweather.entity.City;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CityDAO {
    SQLiteDatabase sdb = null;

    public CityDAO(Context ctxt) {
        String cityDBPath = ctxt.getFilesDir() + "/city.db";
        File dbFile = new File(cityDBPath);
        if (!dbFile.exists()) {
            copyDB(ctxt, cityDBPath);
        }
        sdb = SQLiteDatabase.openOrCreateDatabase(cityDBPath, null);
    }

    private void copyDB(Context ctxt, String dbPath) {
        InputStream in = ctxt.getResources().openRawResource(R.raw.city);
        File dbFile = new File(dbPath);
        int leng = -1;
        byte[] buffer = new byte[1024 * 4];
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dbFile));
            BufferedInputStream bis = new BufferedInputStream(in);
            while ((leng = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, leng);
            }
            bis.close();
            in.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * 根据城市名查询城市
     */
    public City findCityByName(String cityName) {
        City city = null;
        Cursor cityCursor = sdb.query("city", null, "cityname=?", new String[] { cityName }, null, null, null);
        if (cityCursor.moveToNext()) {
            city = City.fromCursor(cityCursor);
        }
        cityCursor.close();
        return city;
    }

    /*
     * 查询所有城市
     */
    public Cursor getAllCity() {
        return sdb.query("city", null, null, null, null, null, null);
    }

    /** 热门城市 **/
    public ArrayList<String> getHotCity() {
        ArrayList<String> cityList = new ArrayList<String>();
        Cursor cursor = sdb.query("city", null, " hotcity = 'Y'", null, null, null, null);
        while (cursor.moveToNext()) {
            String city_name = cursor.getString(cursor.getColumnIndex("cityname"));
            cityList.add(city_name);
        }
        cursor.close();
        return cityList;
    }

    /*
     * 关闭数据库
     */
    public void closeDB() {
        if (sdb != null) {
            sdb.close();
        }
    }

    public ArrayList<String> getAllCityName() {
        Cursor cursor = sdb.query("city", null, null, null, null, null, null);
        ArrayList<String> cityList = new ArrayList<String>();
        while (cursor.moveToNext()) {
            cityList.add(cursor.getString(cursor.getColumnIndex("cityname")));
        }
        cursor.close();
        return cityList;
    }

}